articles

home / developersection / articles / c# anonymous methods – a beginner's guide

C# Anonymous Methods – A Beginner's Guide

C# Anonymous Methods – A Beginner's Guide

Anubhav Kumar 779 22-Apr-2025

In C#, code is safe by default, meaning the .NET runtime ensures type safety and memory safety. However, in special scenarios where you need direct memory access, C# allows you to write unsafe code. At the same time, C# supports multithreading for building responsive and high-performance applications.

Unsafe Code in C#

Unsafe code means the compiler and runtime won’t enforce memory safety checks. It is mostly used when working with pointers, interop, or performance-critical sections.

When to Use Unsafe Code:

  1. Interacting with legacy C/C++ code via P/Invoke.
  2. High-performance memory manipulation.
  3. Working with hardware or memory buffers.

Enabling Unsafe Code

  1. To use unsafe code, you must:
  2. Use the unsafe keyword.
  3. Enable "Allow unsafe code" in your project settings.

Example: Using Unsafe Code with Pointers

using System;

class Program
{
    static unsafe void Main()
    {
        int x = 10;
        int* ptr = &x;

        Console.WriteLine("Value: " + *ptr); // Output: Value: 10
    }
}

Key Unsafe Keywords:

Keyword Description
unsafe Marks code block as unsafe
fixed Pins variable in memory
sizeof Gets size of type in bytes
& Gets address of a variable
* Pointer dereferencing

Notes:

  1. Unsafe code can cause crashes if misused.
  2. Best practice is to limit unsafe blocks only where absolutely necessary.
  3. Requires full trust (cannot run in sandboxed environments).

Multithreading in C#

Multithreading allows a program to execute multiple tasks at once. C# provides rich support through the System.Threading namespace.

Why Use Multithreading?

  1. Improves application responsiveness.
  2. Speeds up computation by parallel processing.
  3. Enables background operations without freezing the UI.

Basic Thread Example

using System;
using System.Threading;

class Program
{
    static void PrintNumbers()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine($"Number: {i}");
            Thread.Sleep(500);
        }
    }

    static void Main()
    {
        Thread thread = new Thread(PrintNumbers);
        thread.Start();

        Console.WriteLine("Main thread finished.");
    }
}

Useful Multithreading Classes

Class/Interface Purpose
Thread Basic thread class
ThreadPool Efficient background thread management
Task Modern async programming abstraction
lock Ensures thread-safe code execution
Monitor, Mutex Advanced synchronization

Thread Safety with lock

To avoid data corruption when multiple threads access shared data, use lock.

class Counter
{
    private int count = 0;
    private object locker = new object();

    public void Increment()
    {
        lock (locker)
        {
            count++;
        }
    }
}

Multithreading Tips

Avoid race conditions by synchronizing shared data.

  1. Use Thread.Sleep or Thread.Join wisely to control thread flow.
  2. Prefer Task and async/await for modern multi-threaded code.
  3. Use lock, Monitor, or concurrent collections to ensure thread safety.

Summary

Topic Unsafe Code Multithreading
Purpose Low-level memory manipulation Run multiple tasks simultaneously
Enabled With unsafe keyword Thread, Task, async/await
Use Case Pointers, performance-critical Background tasks, UI responsiveness
Risk High (memory access errors) Medium (race conditions)

Final Thoughts

  1. Unsafe code gives you C/C++-like control — but handle with care.
  2. Multithreading boosts performance and responsiveness — but demands good synchronization.

Let me know if you’d like to see:

  1. Parallel programming with Task and async/await
  2. Practical multithreading UI examples
  3. More in-depth memory pointer tricks in unsafe code

 


c# c# 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By